package com.keller.seckill.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keller.seckill.mapper.OrderMapper;
import com.keller.seckill.pojo.Order;
import com.keller.seckill.pojo.SecKillGoods;
import com.keller.seckill.pojo.SecKillOrder;
import com.keller.seckill.pojo.User;
import com.keller.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ISecKillGoodsService seckillGoodsService;

    @Autowired
    private ISecKillOrderService seckillOrderService;

    public Order seckill(User user, GoodsVo goods) {
        //秒杀商品表减库存
        SecKillGoods seckillGoods = seckillGoodsService.getOne(new
                QueryWrapper<SecKillGoods>().eq("goods_id",
                goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
        seckillGoodsService.updateById(seckillGoods);
        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSecKillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //生成秒杀订单
        SecKillOrder seckillOrder = new SecKillOrder();
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrderService.save(seckillOrder);
        return order;
    }
}
